package com.nian.hbase.base.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.annotation.PreDestroy;

/**
 * 配置文件
 * @author zhangmj
 * @date 2020/4/22 18:02
 */
@Slf4j
@org.springframework.context.annotation.Configuration
public class HBaseConfig {

    @Value("${hbase.zookeeper.quorum}")
    private String quorum;

    @Value("${hbase.zookeeper.property.clientPort}")
    private String clientPort;

    public static final String PARAM_NAME_HADOOP_HOME_DIR = "hadoop.home.dir";
    /**
     * 开发时 如果出现异常：java.io.FileNotFoundException: HADOOP_HOME
     * 这个不影响使用
     * 需要在本地安装一个hadoop，并且需要单独下 winutils.exe、winutils.pdb 文件
     * 具体操作请自行百度
     */
    public static final String PARAM_NAME_HADOOP_HOME_DIR_V = "G:\\Program Files\\hadoop-3.2.1";
    private static Connection connect;

    public Configuration hBaseConfiguration(){
        System.setProperty(PARAM_NAME_HADOOP_HOME_DIR, PARAM_NAME_HADOOP_HOME_DIR_V);
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", quorum);
        conf.set("hbase.zookeeper.property.clientPort", clientPort);
        return conf;
    }

    @Bean("hBaseConnect")
    public Connection connect(){
        log.info("****************** 建立 HBase 接口 ******************");
        try {
            if(connect == null || connect.isClosed()){
                Configuration conf = hBaseConfiguration();
                connect = ConnectionFactory.createConnection(conf);
            }
        }catch (Exception e){
            log.error("初始化HBase 接口错误:", e);
        }
        return connect;
    }

    @PreDestroy
    public void close(){
        log.info("****************** 关闭 HBase 接口 ******************");
        try {
            if(connect != null && !connect.isClosed()){
                connect.close();
            }
        }catch (Exception e){
            log.error("关闭 HBase 接口错误:", e);
        }
    }
}
